package com.googlecode.protoserv;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.googlecode.protoserv.Protocol.RequestProto;
import com.googlecode.protoserv.Protocol.RpcStatus;

@SuppressWarnings("rawtypes")
public class RpcChannel {

  public static RpcChannel newChannel(String rawurl) {
    URL url = null;
    try {
      url = new URL(rawurl);
    } catch (MalformedURLException e) {
      throw new IllegalArgumentException(e);
    }
    final String protocol = url.getProtocol().toLowerCase();
    if (protocol.equals("http") || protocol.equals("https")) {
      return new RpcChannel(new HttpTransport(url));
    }
    if (protocol.equals("tcp")) {
      if (url.getPath() != null && !url.getPath().isEmpty()) {
        throw new IllegalArgumentException(
            "TCP channel does not support paths.");
      }
      return new RpcChannel(new TcpTransport(url));
    }
    throw new RuntimeException("Unsupport protocol: " + protocol);
  }

  private RpcTransport transport;

  private RpcChannel(RpcTransport transport) {
    this.transport = transport;
  }

  public void invoke(Rpc rpc, RequestProto.Builder requestProto) {
    try {
      if (!this.transport.isOpen()) {
        this.transport.open();
      }
      this.transport.send(rpc, requestProto);
    } catch (IOException e) {
      rpc.setResponse(RpcStatus.NETWORK_ERROR, e.getMessage());
    }
  }
}
